package com.magicode.screen.util;

import com.loopj.android.http.RequestParams;
import com.magicode.screen.AppContext;
import com.magicode.screen.wxapi.MD5Util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by magicode on 12/27/16.
 */

public class Md5TimeSignUtil {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    /**
     * 根据url和参数进行加密
     * @param partUrl 例如:apptest.media.cn/mobile/main/v/channel?id=123456
     * @param params 例如:channelId=123456&abcd=1234
     * @return
     */
    public static Md5TimeSignUtil.Md5SignClass getMd5Sign(String partUrl , RequestParams params){
        String timeSignKey = "timeSign";
        String sign = "sign";
//        params;
//        String saltValue = "screen";
      String saltValue = UIHelper.getUrlSalt(AppContext.getInstance());
//        http://apptest.media.cn/mobile/main/v/channel?id=123456&channelId=123456&abcd=1234
//        String keys = null;
//        if(params != null){
//            keys = params.toString();
//        }
        Md5TimeSignUtil.Md5SignClass result = new Md5TimeSignUtil.Md5SignClass();
        String paraParamStr = null;
//        将url中的参数,写入RequestParam
        if(partUrl != null && partUrl.indexOf("?") != -1){
            paraParamStr = partUrl.substring(partUrl.indexOf("?")+1,partUrl.length());
            partUrl = partUrl.substring(0,partUrl.indexOf("?"));
        }
        Map<String,String> tempCV = getMap(paraParamStr);
        if(tempCV != null) {
            for (String key : tempCV.keySet()) {
                params.put(key, tempCV.get(key));
            }
        }
//        添加时间戳
        Date date = new Date();
        String timeSign = sdf.format(date);
        if(params == null){
            params = new RequestParams();
        }
        params.put(timeSignKey,timeSign);



        Map<String,String> cv = null;
        if(params != null){
            cv = getMap(params.toString());
        }
        Object[] keyArrays = null;
        try{
            if(cv != null) {
                keyArrays = (Object[]) cv.keySet().toArray();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        List keyList = null;
        if(keyArrays != null){
            keyList = Arrays.asList(keyArrays);
        }

        if(keyList != null && keyList.size() > 1) {
            Collections.sort(keyList);
        }
        String resultUrl = "?";

        resultUrl = getStringByMap(partUrl,cv,keyList);

        String encodeUrl = getEncodeStringByMap(partUrl,cv,keyList);

        if(resultUrl.indexOf("/") != 0){
            resultUrl = "/"+resultUrl;
        }
        params.put(sign, MD5Util.MD5Encode(resultUrl+saltValue,"utf-8"));

        try{
            result.url = encodeUrl;
        }
        catch (Exception e){
            e.printStackTrace();
        }
        result.params = params;

        return result;
    }

    /**
     * 根据url,ContentValues,以及带排序的keyList,得到拼装后的字符串
     * @param url
     * @param cv
     * @param keyList
     * @return
     */
    public static String getStringByMap(String url , Map cv,List<String> keyList){
        String result = "?";
        if(keyList == null || keyList.size() == 0 || cv.keySet().isEmpty()){
            result = "";
        }
        for(String key : keyList){
            String value = (String)cv.get(key);
            result += key + "="+cv.get(key)+"&";
        }
        if(keyList.size() > 0){
            result = result.substring(0,result.length() - 1);
        }
        result = url + result;
        return result;
    }

    /**
     * 根据url,ContentValues,以及带排序的keyList,得到拼装后的字符串
     * @param url
     * @param cv
     * @param keyList
     * @return
     */
    public static String getEncodeStringByMap(String url , Map<String,String> cv,List<String> keyList){
        String result = "?";
        if(keyList == null || keyList.size() == 0 || cv.keySet().isEmpty()){
            result = "";
        }
        for(String key : keyList){
            String value = (String)cv.get(key);
            try {
                result += key + "="+URLEncoder.encode((String)cv.get(key),"utf-8")+"&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(keyList.size() > 0){
            result = result.substring(0,result.length() - 1);
        }
        result = url + result;
        return result;
    }

    public static Map<String,String> getMap(String str ){

        return getMap(str,"&","=");
    }
    /**
     * 将字符串拆分为键值对
     * @param str 字符串
     * @param intervalCharacter 间隔符,默认为 &
     * @param equalCharater 等号符,默认为 =
     * @return
     */
    public static Map<String,String> getMap(String str , String intervalCharacter , String equalCharater ){
        if(str == null){
            return null;
        }
        Map result = new HashMap();
        String[] keyValues = str.split(intervalCharacter);
        List<String>  keyList = new ArrayList();

        for(String keyValue : keyValues){
            int ml =keyValue.indexOf(equalCharater);
            String key = keyValue.substring(0,ml);
            String value = keyValue.substring(ml+1,keyValue.length());
            keyList.add(key);
            result.put(key,value);
        }

        return result;
    }

    /**
     * MD5加密类
     */
    public static class Md5SignClass{
        public String url;
        public RequestParams params;
    }
//    @param partUrl 例如:apptest.media.cn/mobile/main/v/channel?id=123456
//            * @param params 例如:channelId=123456&abcd=7890
    public static void main(String args[]){
        String url = "http://apptest.media.cn/mobile/main/v/channel?channelId=123456";
        RequestParams rp = new RequestParams();
        rp.put("channelId","123456");
        rp.put("abcd","7890");
        Md5SignClass msc = Md5TimeSignUtil.getMd5Sign(url,rp);
        System.out.println("url:"+msc.url);
        System.out.println("params:"+msc.params);
    }
}